<!-- 购买商品 -->
<template>
  <view class="product-detail-container">
    <!-- 商品图片轮播 -->
    <swiper class="image-swiper" :autoplay="true" :interval="3000" :circular="true">
      <swiper-item v-for="(img, index) in productImages" :key="index">
        <image :src="img" mode="aspectFill" class="swiper-image" />
      </swiper-item>
    </swiper>

    <!-- 商品基本信息 -->
    <view class="product-info">
      <text class="product-name">{{ product.name }}</text>
      <view class="price-container">
        <text class="product-price">¥{{ product.price.toFixed(2) }}</text>
        <view class="quantity-selector">
          <text class="quantity-label">数量:</text>
          <view class="quantity-control">
            <button class="quantity-btn" @tap="decreaseQuantity">-</button>
            <text class="quantity-value">{{ quantity }}</text>
            <button class="quantity-btn" @tap="increaseQuantity">+</button>
          </view>
        </view>
      </view>
      <text class="product-desc">{{ product.description }}</text>
      <view class="product-meta">
        <text class="meta-label">库存:</text>
        <text class="meta-value">{{ product.stock }}件</text>
        <text class="meta-label">销量:</text>
        <text class="meta-value">{{ product.sales }}+</text>
      </view>
    </view>

    <!-- 商品详情分隔线 -->
    <view class="divider"></view>

    <!-- 商品详情内容 -->
    <view class="product-details">
      <view class="detail-section">
        <text class="section-title">商品详情</text>
        <text class="section-content">{{ product.details }}</text>
      </view>

      <view class="detail-section">
        <text class="section-title">工艺师</text>
        <text class="section-content">{{ product.craftsman }}</text>
      </view>

      <view class="detail-section">
        <text class="section-title">规格参数</text>
        <view class="spec-item" v-for="(spec, index) in specs" :key="index">
          <text class="spec-label">{{ spec.label }}:</text>
          <text class="spec-value">{{ spec.value }}</text>
        </view>
      </view>
    </view>

    <!-- 修改后的底部操作栏 -->
    <view class="action-bar">
      <view class="action-btn cart-btn" @tap="addToCart">
        <uni-icons type="cart" size="24" color="#333"></uni-icons>
        <text>加入购物车</text>
      </view>
      <view class="action-btn buy-btn" @tap="buyNow">
        <text>立即购买(¥{{ (product.price * quantity).toFixed(2) }})</text>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import shuju from '../../../shuju.json';

interface Product {
  id: number;
  name: string;
  price: number;
  description: string;
  details: string;
  craftsman: string;
  imageUrl: string;
  categoryId: number;
  stock: number;
  sales: number;
}

const product = ref<Product>({
  id: 0,
  name: '',
  price: 0,
  description: '',
  details: '',
  craftsman: '',
  imageUrl: '',
  categoryId: 0,
  stock: 0,
  sales: 0
});

// 商品图片列表
const productImages = ref<string[]>([]);

// 规格参数
const specs = ref<{label: string, value: string}[]>([]);

// 购买数量
const quantity = ref(1);

onLoad((options) => {
  if (options.product) {
    const productData = JSON.parse(decodeURIComponent(options.product));
    product.value = productData;
    
    // 设置商品图片（这里使用详情图，实际项目中可能有多个详情图）
    productImages.value = [productData.imageUrl];
    
    // 解析规格参数
    parseSpecs(productData.details);
  }
});

// 增加数量
const increaseQuantity = () => {
  if (quantity.value < product.value.stock) {
    quantity.value++;
  }
};

// 减少数量
const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--;
  }
};

// 解析商品详情中的规格参数
const parseSpecs = (details: string) => {
  const specLines = details.split('\n');
  const specPatterns = [
    { label: '材质', pattern: /^材质：(.+)/ },
    { label: '尺寸', pattern: /^尺寸：(.+)/ },
    { label: '套装内含', pattern: /^套装内含：(.+)/ },
    { label: '适合人群', pattern: /^适合人群：(.+)/ },
    { label: '制作工艺', pattern: /^制作工艺：(.+)/ },
    { label: '特色', pattern: /^特色：(.+)/ },
    { label: '收藏价值', pattern: /^收藏价值：(.+)/ }
  ];
  
  const specsList = [];
  for (const line of specLines) {
    for (const pattern of specPatterns) {
      const match = line.match(pattern.pattern);
      if (match && match[1]) {
        specsList.push({
          label: pattern.label,
          value: match[1].trim()
        });
      }
    }
  }
  
  specs.value = specsList;
};

// 加入购物车
const addToCart = () => {
  if (quantity.value > product.value.stock) {
    uni.showToast({
      title: '库存不足',
      icon: 'none'
    });
    return;
  }

  const cartItem = {
    ...product.value,
    quantity: quantity.value,
    selected: true
  };
  
  let cart = uni.getStorageSync('cart') || [];
  const existingItemIndex = cart.findIndex(item => item.id === product.value.id);
  
  if (existingItemIndex !== -1) {
    const newQuantity = cart[existingItemIndex].quantity + quantity.value;
    if (newQuantity <= product.value.stock) {
      cart[existingItemIndex].quantity = newQuantity;
    } else {
      cart[existingItemIndex].quantity = product.value.stock;
      uni.showToast({
        title: '已达到库存上限',
        icon: 'none'
      });
      return;
    }
  } else {
    if (quantity.value <= product.value.stock) {
      cart.push(cartItem);
    } else {
      uni.showToast({
        title: '库存不足',
        icon: 'none'
      });
      return;
    }
  }
  
  uni.setStorageSync('cart', cart);
  
  // 显示加入购物车成功的提示
  uni.showToast({
    title: '已加入购物车',
    icon: 'success',
    duration: 1500
  });
};

// 立即购买
const buyNow = () => {
  if (quantity.value > product.value.stock) {
    uni.showToast({
      title: '库存不足',
      icon: 'none'
    });
    return;
  }
  
  // 准备完整的商品数据
  const productToBuy = {
    id: product.value.id,
    name: product.value.name,
    price: product.value.price,
    quantity: quantity.value,
    imageUrl: product.value.imageUrl,
    craftsman: product.value.craftsman,
    details: product.value.details,
    specs: specs.value,
    totalPrice: product.value.price * quantity.value
  };
  
  // 跳转到购买页面，传递商品信息
  uni.navigateTo({
    url: '/pages/goumai/goumai?product=' + encodeURIComponent(JSON.stringify(productToBuy))
  });
};
</script>

<style lang="scss">
.product-detail-container {
  padding-bottom: 120rpx;
  background-color: #f7f7f7;
  min-height: 100vh;
}

.image-swiper {
  height: 500rpx;
  
  .swiper-image {
    width: 100%;
    height: 100%;
  }
}

.product-info {
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
  
  .product-name {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 16rpx;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }
  
  .price-container {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    .product-price {
      font-size: 40rpx;
      color: #ff4d4f;
      font-weight: bold;
      margin-right: 30rpx;
    }
    
    .quantity-selector {
      display: flex;
      align-items: center;
      
      .quantity-label {
        font-size: 28rpx;
        color: #666;
        margin-right: 10rpx;
      }
      
      .quantity-control {
        display: flex;
        align-items: center;
        
        .quantity-btn {
          width: 50rpx;
          height: 50rpx;
          line-height: 50rpx;
          text-align: center;
          border: 1rpx solid #ddd;
          background-color: #f7f7f7;
          padding: 0;
          margin: 0;
          font-size: 32rpx;
          
          &:active {
            background-color: #eee;
          }
        }
        
        .quantity-value {
          width: 80rpx;
          text-align: center;
          font-size: 28rpx;
          margin: 0 10rpx;
        }
      }
    }
  }
  
  .product-desc {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 20rpx;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }
  
  .product-meta {
    display: flex;
    flex-wrap: wrap;
    font-size: 24rpx;
    color: #999;
    
    .meta-label {
      margin-right: 10rpx;
    }
    
    .meta-value {
      color: #ff4d4f;
      margin-right: 20rpx;
    }
  }
}

.divider {
  height: 20rpx;
  background-color: #f7f7f7;
}

.product-details {
  background-color: #fff;
  padding: 30rpx;
  
  .detail-section {
    margin-bottom: 40rpx;
    
    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
      display: block;
    }
    
    .section-content {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
    }
    
    .spec-item {
      display: flex;
      margin-bottom: 16rpx;
      font-size: 28rpx;
      
      .spec-label {
        color: #999;
        width: 160rpx;
        flex-shrink: 0;
      }
      
      .spec-value {
        color: #333;
        flex: 1;
      }
    }
  }
}

/* 修改后的底部操作栏样式 */
.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  display: flex;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 999;
  
  .action-btn {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 28rpx;
    height: 100%;
    
    &.cart-btn {
      color: #333;
      background-color: #fff;
      border-right: 1rpx solid #eee;
      flex-direction: column;
      
      uni-icons {
        margin-bottom: 6rpx;
      }
      
      text {
        font-size: 20rpx;
      }
    }
    
    &.buy-btn {
      background: linear-gradient(90deg, #ff4d4f, #ff7875);
      color: #fff;
      font-weight: bold;
      font-size: 32rpx;
    }
    
    &:active {
      opacity: 0.8;
    }
  }
}
</style>